var actions = new Object();

actions.noOperation = function(event) {
    event.preventDefault();
    return false;
}

actions.user = {
    signAgreement: function(event) {
        event.preventDefault();
        $(this).hide();
        $(this).next().show();
        return false;
    },
    register: function(event) {
        event.preventDefault();
        var prefix = 'rf-'
        var userInputs = {'name':'', 'email':'', 'username':'', 'password':'', 'verpass':''};
        var badInputs = false;
        $("#registrationForm input").each(function(index) {
            var self = $(this);
            var selfKey = $(this).attr("name").replace(/^rf-/, '');
            var selfInput = $.trim(self.val());
            
            userInputs[selfKey] = selfInput
            
            if (selfKey == "verpass") {
                return true;
            }
            
            var errorMessage = '';
            var blankInput = selfInput.length == 0;
            var unmatchInput = selfKey == "password" && selfInput != $("#registrationForm input#" + prefix + "verpass").val();
            
            if (blankInput) {
                errorMessage = dictionary.locale.message.error.fillInTheBlank;
            } else if (unmatchInput) {
                errorMessage = dictionary.locale.message.error.failedToVerifyPassword;
            }
            
            if (errorMessage.length > 0) {
                dialog.show(errorMessage, true, false, function() {
                    self.focus();
                });
                badInputs = true;
                return false;
            }
            return true;
        });
        if (badInputs) {
            return false;
        }
        dialog.show(dictionary.locale.message.event.waitingDuringRegistration);
        call("users", userInputs,
            function(response) {
                dialog.show(dictionary.locale.message.event.successfulRegistration, true, false, function() {
                    $("#a-signin").click();
                });
            },
            function (XMLHttpRequest, textStatus, errorThrown) {
                var errorMessage = '';
                if (XMLHttpRequest.responseText.length == 0) {
                    dialog.show(XMLHttpRequest.statusText, true);
                } else {
                    dialog.show(XMLHttpRequest.responseText, true);
                }
            },
            "post"
        )
        return false;
    }
}

actions.controller = {
    selectCommand: function(event) {
        // no highlight
        if ($(this).attr("id") == "a-create-folder" || $(this).attr("id") == "a-sysabout" || $(this).attr("id") == "a-language-switch") {
            return false;
        }
        // Show file ops
        if ($(this).attr("id") == "a-browse" || $(this).parent().parent().hasClass("iff-browse")) {
            $(".iff-browse").slideDown();
        // Hide file ops
        } else {
            $(".iff-browse").slideUp();
        }
        $("#controller a").parent().removeClass("e-selected");
        $(this).parent().addClass("e-selected");
        return true;
    },
    showAbout: function (event) {
        event.preventDefault();
        $("#dialog .dialog-section").hide();
        $("#sysabout").show();
        dialog.show();
    },
    showLanguageSwitch: function (event) {
        event.preventDefault();
        $("#dialog .dialog-section").hide();
        $("#language-switch").show();
        dialog.show();
    },
    doLanguageSwitch: function (event) {
        event.preventDefault();
        window.location.href = String(window.location.href).replace(/\?.*/, '') + "?" + $(this).val();
    },
    promptToUpload: function() {
        $("#display > div").hide();
        $("#uploader #upload-inputs input").val("");
        $("#uploader").show();
        $("#uploader-limit").html(getReadableFilesize(uploadQuota))
        $("#uploader-location").html(lastAccessedLocation == ''?dictionary.locale.label.homeDirectory:lastAccessedLocation)
    },
    showSiteInfo: function() {
        var userSite = userSiteBase + (userSiteBase.match(/\/$/)?'':'/') + userID;
        $("#display > div").hide();
        $("#site-info h2 span").html(userRealName);
        $("#site-info img").attr("src",
            "http://chart.apis.google.com/chart?"
            + "chs=380x250"
            + "&cht=p"
            + "&chco=4D89F9,215498"
            + "&chd=t:" + (userUsage*100/userQuota) + "," + ((userQuota - userUsage)*100/userQuota)
            + "&chl=Used|Remaining&cached=shiroyuki.png"
        );
        $("#site-info #user-site").html(userSite);
        $("#site-info #user-site").attr("href", userSite);
        $("#site-info #user-site").attr("target", "_blank");
        $("#site-info #user-usage").html(getReadableFilesize(userUsage));
        $("#site-info #user-quota").html(getReadableFilesize(userQuota));
        $("#site-info").show();
        
    },
    switchToNAUTHMode: function() {
        var targetArea = String($(this).attr("id")).replace(/^a-/, "");
        if (targetArea == "signup") {
            $("#" + targetArea).find("form").hide();
            $("#" + targetArea).find("#terms").show();
        }
        $("#user-io > div:not(" + targetArea + ")").hide();
        $("#" + targetArea).show();
        $("#sysabout, #browser").hide();
        $("#user-io").show();
    }
}

actions.filesystem = {
    makeFolder: function(event) {
        event.preventDefault();
        call("storages", {
                directive: 'mkdir',
                location: lastAccessedLocation,
                label: $(this).find("input[type=text]").val()
            },
            function(xmlDoc) {
                browse();
            },
            function() {
                dialog.show(dictionary.locale.message.error.cannotCreateFolder, false, true);
            },
            "post"
        );
        return false;
    },
    upload: function(event) {
        if ($("#uploader #upload-inputs li").length < 2) {
            event.preventDefault();
            dialog.show(dictionary.locale.message.error.haveNotSelectFile, true);
            return false;
        }
        
        dialog.showActionInMotion(dictionary.locale.message.event.uploadInProgress);
        
        $("input[name=userID]").val(userID);
        $("input[name=location]").val(lastAccessedLocation);
        
        return true;
    },
    uploadFailed: function(event) {
        dialog.show(dictionary.locale.message.error.failedToAddFiles, true);
    },
    uploadSucceeded: function(event) {
        dialog.show(dictionary.locale.message.event.sucessfulUploading, true);
        $("#a-add-files").click();
    },
    browse: function(event) {
        var destination = '';
        // Entry point: Directory icon
        if ($(this).attr("id") != "a-browse" && typeof(lastAccessedLocation) != "undefined") {
            destination = $(this).find(".dn").text();
            if (lastAccessedLocation != '') {
                destination = lastAccessedLocation + '/' + destination
            }
        }
        // Entry point: LHS controller
        if ($(this).attr("id") == "a-browse" && typeof(lastAccessedLocation) != "undefined") {
            destination = lastAccessedLocation;
        }
        // Entry point: Breadcrumb
        if ($(this).hasClass('location-path')) {
            destination = $(this).attr("path");
            
        }
        
        browse(destination);
    },
    move: function(event) {
        dialog.showActionInMotion(dictionary.locale.message.event.movingInProgress);
        var options = {
            source: [],
            destination: []
        }
        $("#browser-stock .entry").find(".fn,.dn").each(function(index) {
            var source = getCleanFilePath($(this).attr("base") + "/" + $(this).text());
            var target = getCleanFilePath(lastAccessedLocation + "/" + $(this).text());
            options.source.push(source);
            options.destination.push(target);
        });
        options.source = options.source.join(',')
        options.destination = options.destination.join(',')
        call("storages/" + userID, options,
            function(xmlDoc) {
                ui.state.afterSuccessfulBatchOperation(event);
            },
            function() {
                ui.state.afterFailedBatchOperation(event);
            },
            "put"
        );
    },
    remove: function(event) {
        if (!confirm(dictionary.locale.message.event.promptingForRemoving)) {
            return;
        }
        dialog.showActionInMotion(dictionary.locale.message.event.removingInProgress);
        var options = {
            where: []
        }
        $("#browser-stock .entry").find(".fn,.dn").each(function(index) {
            var source = getCleanFilePath($(this).attr("base") + "/" + $(this).text());
            options.where.push(source);
        });
        options.where = options.where.join(',')
        call("storages/" + userID, options,
            function(xmlDoc) {
                ui.state.afterSuccessfulBatchOperation(event);
            },
            function() {
                ui.state.afterFailedBatchOperation(event);
            },
            "delete"
        );
    },
    rename: function(event) {
        if (event.keyCode == 13) {
            $(this).attr("disabled", "disabled");
            var self = $(this).parent();
            self.find("button").remove();
            call("storages/" + userID, {
                    source: getCleanFilePath(self.attr("base") + "/" + self.attr("originalName")),
                    destination: getCleanFilePath(self.attr("base") + "/" + self.find("input").val())
                },
                function(xmlDoc) {
                    self.attr("originalName", self.find("input").val())
                    self.html(self.find("input").val());
                    browse(null, true);
                },
                function() {
                    self.html($(self).attr("originalName"));
                },
                "put"
            );
        }
    },
    renameEnabled: function(event) {
        event.stopPropagation();
        if ($(this).find("input").length > 0) {
            return;
        }
        $(this).attr("originalName", $(this).html());
        $(this).html('<input type="text" value="' + $(this).html() + '"/><button class="gb-remove">x</button>');
        $(this).find("input").focus();
    },
    renameCancelWithButton: function(event) {
        event.stopPropagation();
        $(this).parent().html($(this).parent().attr("originalName"));
        return false;
    },
    renameCancelWithEscKey: function(event) {
        if (event.keyCode == 27) {
            $(this).next().click();
        }
    }
}

actions.stock = {
    toggle: function() {
        if(getNumberOfSelectedItems() == 0) {
            return;
        }
        $("#browser").toggleClass("display-stock");
        $(this).toggleClass("e-selected");
        
        if ($("#browser").hasClass("display-stock")) {
            $("#browser-stock").slideDown();
            $("#browser-forest").slideUp();
        } else {
            $("#browser-stock").slideUp();
            $("#browser-forest").slideDown();
        }
    }
}